#include "CEditListCtrl.h"


BEGIN_MESSAGE_MAP(CItemEdit, CEdit)
	ON_WM_KEYDOWN()
	ON_WM_KILLFOCUS()
END_MESSAGE_MAP()

BEGIN_MESSAGE_MAP(CEditListCtrl, CListCtrl)
	ON_NOTIFY_REFLECT(NM_DBLCLK, &CEditListCtrl::OnNMDblclk)
	ON_WM_MOUSEWHEEL()
END_MESSAGE_MAP()

CEditListCtrl::CEditListCtrl()
{
	m_hitCol = 0;
	m_hitRow = 0;
	m_bEditable = TRUE;
	m_pEdit = NULL;
}

CEditListCtrl::~CEditListCtrl()
{
	m_hitCol = 0;
	m_hitRow = 0;
	m_bEditable = TRUE;
	if (m_pEdit)
	{
		delete m_pEdit;
	}
}

void CEditListCtrl::OnNMDblclk(NMHDR* pNMHDR, LRESULT* pResult)
{
	if (NULL == m_pEdit)
	{
		m_pEdit = new CItemEdit(this);
		m_pEdit->Create(WS_CHILD | ES_LEFT | WS_BORDER | ES_AUTOHSCROLL | ES_WANTRETURN | ES_MULTILINE, CRect(0, 0, 0, 0), this, 1);
	}

	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);

	LVHITTESTINFO info{};
	info.pt = pNMItemActivate->ptAction;

	if (SubItemHitTest(&info) != -1 && m_bEditable == TRUE)
	{
		m_hitRow = info.iItem;
		m_hitCol = info.iSubItem;

		CRect rect;
		GetSubItemRect(m_hitRow, m_hitCol, LVIR_LABEL, rect);

		m_pEdit->SetWindowText(GetItemText(m_hitRow, m_hitCol));
		m_pEdit->MoveWindow(rect, TRUE);
		m_pEdit->ShowWindow(SW_SHOW);
		m_pEdit->SetFocus();
	}
	else
	{
		m_pEdit->ShowWindow(SW_HIDE);
	}

	*pResult = 0;
}

void CEditListCtrl::SetEditable(BOOL bEditable)
{
	m_bEditable = bEditable;
}
